package com.heima.article.service.impl;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.search.vo.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private Configuration configuration;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    @Async
    @Override
    public void buildArticleToMinIO(ApArticle apArticle, String content) {

        //    查询文章详情页面
        QueryWrapper<ApArticleContent> wrapper = new QueryWrapper<>();
        wrapper.eq("article_id", apArticle.getId());
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(wrapper);

        if (StringUtils.isNotBlank(content)) {
//        生成模板
            StringWriter out = null;
            try {
                Template template = configuration.getTemplate("article.ftl");

                //            将json数据转化为对象
                JSONArray jsonArray = JSONArray.parseArray(content);
                System.out.println(jsonArray);
                Map<String, Object> map = new HashMap<>();
                map.put("content", jsonArray);

                out = new StringWriter();
//        获取数据模型
                template.process(map, out);
            } catch (Exception e) {
                e.printStackTrace();
            }

            InputStream inputStream = new ByteArrayInputStream(out.toString().getBytes());

//            把html文件上传到minio中
            String path = fileStorageService.uploadHtmlFile("", apArticleContent.getArticleId() + ".html", inputStream);

//            修改文章详情表
            ApArticle article = new ApArticle();
            article.setId(apArticleContent.getArticleId());
            article.setStaticUrl(path);
            apArticleMapper.updateById(article);


//            发送消息同步文章到ES中
            createESIndexCancle(apArticle, content, path);
        }

    }

    //            发送消息同步文章到ES中
    private void createESIndexCancle(ApArticle apArticle, String content, String path) {

        SearchArticleVo articleVo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle, articleVo);
        articleVo.setContent(content);
        articleVo.setStaticUrl(path);
        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(articleVo));
    }
}
